package com.zxmr.utility.action;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.zxmr.action.Request;
import com.zxmr.action.Response;
import com.zxmr.action.ResponsePayload;
import com.zxmr.action.ResultCode;
import com.zxmr.domain.Task;
import com.zxmr.domain.TaskState;
import com.zxmr.domain.service.TaskSearchBean;
import com.zxmr.domain.service.TaskService;
import com.zxmr.navigate.ExecuteException;
import com.zxmr.navigate.Executor;
import com.zxmr.util.Utils;
import com.zxmr.utility.dto.JSONListDTO;

public class MyTask extends Executor{
	
	@Override
	public void execute(Request request, Response response) {
		
		try
		{
			int start = getStart(request);
			int limit = getLimit(request);
			String type = getRequestType(request);
			TaskState state = getTaskState(request);
			
			TaskSearchBean searchBean = new TaskSearchBean();
			searchBean.setCompany(request.getAccount().getCompany());
			searchBean.setStart(start);
			searchBean.setLimit(limit);
			searchBean.setState(state);
			if(type.equals("assigner"))
				searchBean.setAssigner(request.getAccount().getName());
			else
				searchBean.setAssignee(request.getAccount().getName());
			
			TaskService service = new TaskService();
			List<Task> task = service.queryContractPagination(searchBean);
			int count = service.queryContractPaginationCount(searchBean);
			
			JSONListDTO dto = new JSONListDTO();
			dto.setRows(task);
			dto.setTotal(count);
			
			ResponsePayload payload = new ResponsePayload(JSON.toJSONString(dto));
			response.setPayload(payload);

		}catch(Exception e)
		{
			ResponsePayload payload = new ResponsePayload();
			if(e instanceof ExecuteException)
			{
				payload.setValue(e.getMessage());
			}else
			{
				e.printStackTrace();
				payload.setValue("internal error");
			}
			response.setPayload(payload);
			response.setResult(ResultCode.COMPONENT_ERROR);
		}
	}
	
	private int getStart(Request request)throws ExecuteException
	{
		try
		{
			return Integer.parseInt(request.getRequestParameters().get("start"));
		}catch(Exception e)
		{
			throw new ExecuteException("start parameter is not valid");
		}
	}
	
	private int getLimit(Request request)throws ExecuteException
	{
		try
		{
			return Integer.parseInt(request.getRequestParameters().get("limit"));
		}catch(Exception e)
		{
			throw new ExecuteException("limit parameter is not valid");
		}
	}
	private String getRequestType(Request request)throws ExecuteException
	{
		String type = request.getRequestParameters().get("type");
		if("assigner".equals(type))
			return type;
		
		return "assignee";	
	}
	private TaskState getTaskState(Request request)throws ExecuteException
	{
		String type = request.getRequestParameters().get("state");
		if(Utils.isStringEmptyWithTrim(type))return null;
		try
		{
			return TaskState.valueOf(type);
		}catch(Exception e)
		{
			throw new ExecuteException("task state parameter is not valid");
		}
	}
}
